package com.xyzwps.benchmarks.json;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.adapter.JsonbAdapter;
import java.util.Date;

public class YassonUtils implements JsonUtils {

    private static final Jsonb jsonb = JsonbBuilder.create(new JsonbConfig()
            .withAdapters(new DateTimestampAdapter())
            .withNullValues(true));

    @Override
    public String stringify(Object obj) {
        return jsonb.toJson(obj);
    }

    @Override
    public <T> T parse(String s, Class<T> c) {
        return jsonb.fromJson(s, c);
    }

    public static class DateTimestampAdapter implements JsonbAdapter<Date, Long> {

        @Override
        public Long adaptToJson(Date obj) {
            return obj.getTime();
        }

        @Override
        public Date adaptFromJson(Long obj) {
            return new Date(obj);
        }
    }

    public static final YassonUtils INSTANCE = new YassonUtils();
}
